﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Web;
using System.Web.Mvc;
using Identity.Infrastructure;
using Identity.ViewModels;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using System.Threading.Tasks;
using IBusinessLogicLayer;
using Identity.Models;

namespace MVC.Controllers
{
    [Authorize]
    public class AccountController : Controller
    {
        private AppUserManager UserManager
        {
            get { return HttpContext.GetOwinContext().GetUserManager<AppUserManager>(); }
        }

        private IAuthenticationManager AuthManager
        {
            get { return HttpContext.GetOwinContext().Authentication; }
        }
        private IShoppingCartBll shoppingCartBll { get; set; }

        public AccountController(IShoppingCartBll bll)
        {
            shoppingCartBll = bll;
        }
        [AllowAnonymous]
        // GET: Account
        public ActionResult Login(string returnUrl)
        {
            ViewBag.returnUrl = string.IsNullOrEmpty(returnUrl)?"/Home/Index":returnUrl;
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        // GET: Account/Details/5
        public async Task<ActionResult> Login(LoginModel details,string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByEmailAsync(details.Email);
                if (user != null)
                {
                    var verifyResult = UserManager.PasswordHasher.VerifyHashedPassword(user.PasswordHash,
                        details.Password);
                    if (verifyResult == PasswordVerificationResult.Success)
                    {
                        ClaimsIdentity ident =
                            await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
                        AuthManager.SignOut();
                        AuthManager.SignIn(new AuthenticationProperties {IsPersistent = false}, ident);


                        //将Cookie中的Cart信息存储到当前用户，并清空cookie
                        shoppingCartBll.SaveCartsFromCookie(AuthManager.User.Identity.GetUserId());

                        return Redirect(returnUrl);
                    }
                    else
                    {
                        ModelState.AddModelError("", "Invalid name or password");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user is not exsited");
                }
            }
            ViewBag.returnUrl = returnUrl;
            return View();
        }


        public ActionResult SignOut()
        {
            AuthManager.SignOut();
            return RedirectToAction("Index","Home");
        }
        [AllowAnonymous]
        public ActionResult Register(string returnUrl)
        {
            ViewBag.returnUrl = string.IsNullOrEmpty(returnUrl) ? "/Home/Index" : returnUrl;
            if(HttpContext.User.Identity.IsAuthenticated)
                return RedirectToAction("Index","Home");
            return View();
        }
        [AllowAnonymous]
        [HttpPost]
        public ActionResult Register(RegisterModel details,string returnUrl)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    // TODO: Add insert logic here
                    var result = UserManager.Create(new AppUser() { Email = details.Email, UserName = details.Email }, details.Password);
                    if (result.Succeeded)
                    {
                        ClaimsIdentity ident = UserManager.CreateIdentity(UserManager.FindByEmail(details.Email),
                            DefaultAuthenticationTypes.ApplicationCookie);
                        AuthManager.SignOut();
                        AuthManager.SignIn(new AuthenticationProperties {IsPersistent = false}, ident);
                        shoppingCartBll.SaveCartsFromCookie(AuthManager.User.Identity.GetUserId());
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        ModelState.AddModelError("","failed, please try again.");
                    }  
                }
            }
            catch
            {
               // 
            }
            ViewBag.returnUrl = returnUrl;
            return View();
        }

        // GET: Account/Edit/5
        public ActionResult Edit(int id)
        {
            return View();
        }

        // POST: Account/Edit/5
        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: Account/Delete/5
        public ActionResult Delete(int id)
        {
            return View();
        }

        // POST: Account/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
